define(function(require, exports, module) {

  'use strict';

  var Select = require('select');

  var io = require('../io');

  /**
   * Select
   * 添加异步支持，通过属性配置
   *
   * @class [description]
   * @return {[type]}           [description]
   */
  var MySelect = Select.extend({

    defaults: {
      // 请求额外参数
      params: {},
      // 请求地址
      url: null,
      // 有全部选项
      hasOptionAll: true,
      delimiter: ':',
      load: function(callback) {
        var self = this;

        io.get(self.option('url'),
          self.option('params'),
          function(data) {
            var model,
              hasOptionAll = self.option('hasOptionAll');

            if (this.data.listData === null || this.data === null) {
              model = [];
            } else {
              model = this.data.listData || this.data;
            }

            model = self.transformModel(model);

            //self.fire('transform', model);

            if (hasOptionAll) {
              model.unshift({
                value: '',
                text: '全部'
              });
            }

            callback(model);
          });
      }
    },
    // 转换 model
    transformModel: function(model) {
      var values = this.field.val(),
        key = this.option('key') || {};

      if (values) {
        values = values.split(this.option('delimiter'));
      }

      model.forEach(function(item) {
        item.text = '' + item[key.text || 'name'];
        item.value = '' + item[key.value || 'id'];
        if (values && values.indexOf(item.value) !== -1) {
          item.selected = true;
        }
      });
      return model;
    },

    setup: function() {
      if (!this.option('url')) {
        this.option('load', null);
      }
      MySelect.superclass.setup.call(this);
    }
    /*,

     getSelectedData: function () {
     var data = [];

     this.data('select').forEach(function (select) {
     if (select.selected) {
     data.push(select);
     }
     });

     return data;
     }*/

  });

  module.exports = MySelect;

});
